import time
import random
from datetime import datetime
from Core import driver_requests
from Core import xs_config as config
from Core import threads


def do_learn(course_uuid, lesson_uuid, lesson_length, lesson_title):
    # =============将课目加入学习==============
    config.XS_Post_Body_CourseUser['course_id'] = course_uuid
    MyReq.http_post_by_json(config.XS_Post_courseUser_url, config.Headers, config.XS_Post_Body_CourseUser)
    # ======================================
    mine_response = MyReq.http_get_by_json(config.xs_mine_url, headers=config.Headers)
    print("当前学习积分:{} , 学时:{}".format(mine_response['data']['credits'], mine_response['data']['learn_length']))
    learn_time = lesson_length + random.randint(3, 20)
    MyReq.http_get_by_json(config.XS_Get_startLearn_url+lesson_uuid, config.Headers)
    count = 0
    for j in range(learn_time):
        print("\r 正在学习: {} ,时长:{}, 剩余:{}秒".format(lesson_title, lesson_length, learn_time - j), end="")
        if count <= lesson_length and count % 30 == 0:
            config.XS_Post_Body_UpdateWatchTime['lesson_id'] = lesson_uuid
            config.XS_Post_Body_UpdateWatchTime['playing'] = "true"
            config.XS_Post_Body_UpdateWatchTime['learn_time'] = count
            config.XS_Post_Body_UpdateWatchTime['current_time'] = count
            MyReq.http_post_by_json(config.XS_Post_updateWatchTime_url, config.Headers, config.XS_Post_Body_UpdateWatchTime)
        count += 1
        time.sleep(1)
        print("\r", end="")
    MyReq.http_get_by_json(config.XS_Get_finishLearn_url+lesson_uuid+'&course_id='+lesson_uuid, config.Headers)


def do_main():
    curr_time = datetime.now()
    # 学习时间只能在早上7点-19点之间
    if 7 <= curr_time.hour <= 19:
        course_response = MyReq.http_get_by_json(config.xs_course_list_url, config.Headers)
        # print(course_response)
        if course_response['status'] == "ok":
            print(course_response['message'], "总计共:", len(course_response['data']['list'])-1, "课目")
            for i, Course in enumerate(course_response['data']['list']):
                # 获取课程信息
                # print('该课目积分', Course['credit'])
                lesson_response = MyReq.http_get_by_json(config.XS_Get_courseLesson_url+Course['uuid'], config.Headers)
                for Lesson in lesson_response['data']['list']:
                    if Lesson['is_chapter'] == 0 and Lesson['learn_status'] == 'learning' and Course['credit'] != 0 and Lesson['type'] == 'video':
                        print('开始学习:课目{} ({}积分) -----> 课程:{}'.format(Course['title'], str(Course['credit']), Lesson['title']))
                        do_learn(Course['uuid'], Lesson['uuid'], Lesson['length'], Lesson['title'])
    else:
        print("当前时间服务器维护中.")


if __name__ == "__main__":
    start_time = time.time()
    MyReq = driver_requests.DriverRequests()
    config.Headers['Authorization'] = input("请输入Authorization:")
    XS_Thread = threads.MyThread("开始课程学习", do_main, lock=False)
    XS_Thread.start()
    XS_Thread.join()
